


# Do commit

require 'net/http'
require 'uri'
require 'json'

#
def fetch_command(host)

    query = <<QUERY
    {
        "station": "station-rb-test",
        "token": "abcdefg"
    }
QUERY

    url = URI.parse(host + '/cmd/query')
    req = Net::HTTP::Post.new(url.path, {'Content-Type' => 'application/json'})  
    req.body = query  
    res = Net::HTTP.new(url.host, url.port).start{|http| http.request(req)}


    #body = Net::HTTP.get(host, '/command/fetch')
    #TODO: parse body to get command id

    # body should follow this format
    #body = <<COMMAND_FETCHED
    #{
    #	"id": "123334",
    #    "station" : "",
    #	"cmd" : "",
    #    "arg" : "",
    #    "time" : ""
    #}
#COMMAND_FETCHED
    d = JSON.parse(res.body)

    return d['cmd']['id']
end

#
def reply_command(host, command_id)
	puts command_id
	data = <<COMMAND_TO_REPLY
{
    "cmd" : 
    {
        "id" : 11, 
        "reply" : "{\\"result\\" : \\"success\\"}"
    },
	"token" : "abcdefg"
}
COMMAND_TO_REPLY

	url = URI.parse(host + "/cmd/reply")  
    req = Net::HTTP::Post.new(url.path, {'Content-Type' => 'application/json'})  
    req.body = data  
    res = Net::HTTP.new(url.host, url.port).start{|http| http.request(req)}  

    puts res.body

end


def fetch_command_reply(host)
	command_id = fetch_command(host)
	reply_command(host, command_id)
end

fetch_command_reply("http://127.0.0.1")